from pathlib import Path
from typing import Dict, Optional
from django_context_from_path import Node, compile, genContextDict, R
from django.http import HttpRequest
from django.utils.translation import gettext_lazy as _

PSSA_PREFIX = Path("script/app")

class BreadCrumb:
    """
    text: used in `trans` template tag
    view_name: used in `url` template tag
    """
    def __init__(self, text: str, view_name: Optional[str]):
        self.text = text
        self.view_name = view_name

    def __repr__(self) -> str:
        return f"<BreadCrumb {self.text} {self.view_name}>"

def last_path_segment(_request, path: list[str]):
    return path[-1]

CONFIG = compile({
    'app_name': _('北大六院国家药物临床试验机构管理系统'),
    'title': '北大六院国家药物临床试验机构管理系统', # in `trans` tag
    'navbar_sec': None,
    'sidebar_sec': None,
    'breadcrumbs': [],
    'has_page_script': False,
    'page_script_static_path': None,
    'hide_sidebar': False,
    'hide_headline': False,
    
    Node.ROUTES: {
        '__debug_experiment__': {
            'page_script_static_path': 'script/__debug_experiment__.js'
        },
        'docs': {
            'hide_headline': True,
            Node.ROUTES: {
                Node.MATCH_COMPLETE: { 'sidebar_sec': 'index' },
                Node.MATCH_REST: {
                    'sidebar_sec': last_path_segment
                }
            }
        },
        'media': {
            Node.ROUTES: {
                'public': {
                    'title': '公开文件',
                    'navbar_sec': 'resources',
                    'sidebar_sec': 'files',
                    'has_page_script': True,
                    'hide_headline': True,
                    'breadcrumbs': [BreadCrumb('公开资料', 'media:public'), BreadCrumb('文件', None)],
                }
            },
        },
        'audit': {
            'title': '审核',
            'navbar_sec': 'management',
            'breadcrumbs': BreadCrumb('审核', None),
            Node.ROUTES: {
                "user": {
                    'title': '用户注册审核',
                    'has_page_script': True,
                    'sidebar_sec': 'user-registry',
                    'headerline_tab_sec': 'audit-user-registry',
                },
                Node.VIRTUAL: {
                    'page_script_static_path': 'script/app/audit/project.js',
                    'sidebar_sec': 'project-audit',
                    'has_page_script': True,
                    Node.ROUTES: {
                        "project-info": {
                            'title': '项目信息审核',
                            'headerline_tab_sec': 'info',
                        },
                        "project-plan": {
                            'title': '项目方案审核',
                            'headerline_tab_sec': 'plan',
                        },

                        "project-initiation-data": {
                            'title': '项目立项资料审核',
                            'headerline_tab_sec': 'initiation',
                        },

                        "project-before-implement": {
                            'title': '项目启动前审核',
                            'headerline_tab_sec': 'before-implement',
                        },

                        "project-implement": {
                            'title': '项目入组审核',
                            'headerline_tab_sec': 'implement',
                        },

                        "project-finish": {
                            'title': '项目结束审核',
                            'headerline_tab_sec': 'finish',
                        },                        
                    },
                }, # `audit/project-xxx` ends
                "file": {
                    'title': '文件访问申请审核',
                    'has_page_script': True,
                    'sidebar_sec': 'audit-file-access',
                    'breadcrumbs': BreadCrumb('文件访问申请', None),
                }
            },
        },  # `audit` ends
        'user': {
            'title': '用户',
            Node.ROUTES: {
                'researchers': {
                    'title': '研究者列表',
                    'navbar_sec': 'resources',
                    'sidebar_sec': 'researchers',
                    'breadcrumbs': [BreadCrumb('公开资料', 'media:public'), BreadCrumb('研究者列表', None)],
                },
                str.isdigit: {
                    Node.ROUTES: {
                        'profile': {
                            'title': '标题',
                            "hide_sidebar": True,
                            'hide_headline': True,
                            "has_page_script": True,
                        },
                    }
                },
                'settings': {
                    Node.ROUTES: {
                        "profile": {
                            'title': "个人资料",
                            'breadcrumbs': BreadCrumb('个人资料', None),
                            'sidebar_sec': 'profile',
                        },
                        "account": {
                            "title": "账号",
                            'breadcrumbs': BreadCrumb('账号', None),
                            'sidebar_sec': 'account',
                        },
                        "resume": {
                            'title': '简历管理',
                            "has_page_script": True,
                            'breadcrumbs': BreadCrumb('简历管理', None),
                            'sidebar_sec': 'resumes',
                        },
                    },
                },
                "management": {
                    'navbar_sec': 'management',
                    'has_page_script': True,
                    Node.ROUTES: {
                        Node.VIRTUAL: {
                            'sidebar_sec': 'user-common',
                            Node.ROUTES: {
                                "list": {
                                    'title': "所有用户",
                                    'headerline_tab_sec': 'all-users'
                                },
                                "permission": {
                                    'title': '用户权限管理',
                                    'headerline_tab_sec': 'user-permission'
                                },
                                "researchers-resumes": {
                                    'title': '研究者简历管理',
                                    'headerline_tab_sec': 'researchers-resumes'
                                }
                            }
                        },
                        'invite-code': {
                            'title': '邀请码管理',
                            'sidebar_sec': 'user-registry',
                            'headerline_tab_sec': 'invite-code'
                        }
                    }
                }, # `user.management` ends1
            }
        },  # `user` ends
        'project': {
            'title': '项目',
            'navbar_sec': 'project',
            'breadcrumbs': BreadCrumb('项目', 'project:index'),
            Node.ROUTES: {
                Node.MATCH_COMPLETE: {
                    'title': '项目列表',
                    'breadcrumbs': BreadCrumb('我的项目列表', None),
                    'has_page_script': True,
                    'hide_sidebar': True,
                },
                "create": {
                    'title': '创建项目',
                    'sidebar_sec': None,
                    'breadcrumbs': BreadCrumb('创建项目', None),
                },
                "management": {
                    'navbar_sec': 'management',
                    "sidebar_sec": "project",
                    Node.ROUTES: {
                        "list": {
                            "title": "所有项目",
                            'breadcrumbs': BreadCrumb('所有项目列表', None),
                            'has_page_script': True,
                        }
                    }
                },
                str.isdigit: {
                    Node.ROUTES: {
                        Node.MATCH_COMPLETE: { # detail
                            'title': '项目信息',
                            'sidebar_sec': 'information',
                            'breadcrumbs': BreadCrumb('项目信息', None),
                        },
                        "update": {
                            'title': '更新项目',
                            'breadcrumbs': BreadCrumb('更新项目', None),
                        },
                        "audit": {},

                        "plan": {
                            "title": "项目方案",
                            'sidebar_sec': 'plan',
                            'breadcrumbs': BreadCrumb('方案', None),
                            Node.ROUTES: {
                                Node.MATCH_COMPLETE: {
                                    'has_page_script': True,
                                }
                            }
                        }, # `plan` ends
                        "initiation": {
                            "title": "立项资料列表",
                            'sidebar_sec': 'initiation',
                            'breadcrumbs': BreadCrumb('立项资料', None),
                            Node.ROUTES: {
                                Node.MATCH_COMPLETE: {
                                    'has_page_script': True,
                                }
                            }
                        }, # `initiation` ends
                        'ethical_review': {
                            'title': '伦理审查',
                            'sidebar_sec': 'ethical_review',
                            'breadcrumbs': BreadCrumb('伦理审核', None),
                            Node.ROUTES: {
                                Node.MATCH_COMPLETE: {
                                    'has_page_script': True,
                                }
                            },
                        }, # `ethical_review` ends
                        "human_genetic_resource": {
                            "title": "人类遗传资源申请",
                            'sidebar_sec': 'human_genetic_resource',
                            'page_script_static_path': 'script/app/project/human_genetic_resource/base.js',
                            'breadcrumbs': BreadCrumb('人类遗传资源申请', None),
                        }, # `human_genetic_resource` ends
                        "contract": {
                            "title": "合同签署",
                            'sidebar_sec': 'contract',
                            'breadcrumbs': BreadCrumb('合同签署', None),
                            Node.ROUTES: {
                                Node.MATCH_COMPLETE: {
                                    'has_page_script': True,
                                }
                            }
                        }, # `contract` ends
                        'before_implement': {
                            'title': '启动前准备',
                            'sidebar_sec': 'before_implement'
                        },
                        "material": {
                            "title": "项目物资",
                            'sidebar_sec': 'material',
                            'breadcrumbs': BreadCrumb('物资', None),
                            Node.ROUTES: {
                                Node.MATCH_COMPLETE: {
                                    'has_page_script': True,
                                },
                            }
                        }, # `material` ends
                        "beginning": {
                            'title': '项目启动',
                            'sidebar_sec': 'beginning',
                            'breadcrumbs': BreadCrumb('启动', None),
                        },
                        "implement": {
                            'title': '项目入组',
                            'sidebar_sec': 'implement',
                            'breadcrumbs': BreadCrumb('入组', None),
                        },
                        "quality_control": {
                            "title": "质控",
                            'sidebar_sec': 'quality_control',
                            'breadcrumbs': BreadCrumb('质控', None),
                            Node.ROUTES: {
                                Node.MATCH_COMPLETE: {
                                    'has_page_script': True,
                                },
                            }
                        }, # `quality_control` ends
                        "finish": {
                            'title': '项目结束',
                            'sidebar_sec': 'finish',
                            'breadcrumbs': BreadCrumb('结束', None),
                        }, # `finish` ends
                        "examination": {
                            "title": "现场检查",
                            'sidebar_sec': 'examination',
                            'breadcrumbs': BreadCrumb('现场检查', None),
                            Node.ROUTES: {
                                Node.MATCH_COMPLETE: {
                                    'has_page_script': True,
                                },
                            }
                        } # `examination` ends
                    },
                }
            },
        }  # `project` ends
    },
})

def process_config(config: Dict, route_config: Optional[Dict], request: HttpRequest, acc_path: list[str]):
    if not route_config:
        return

    for field, value in route_config.items():
        if callable(value):
            value = value(request, acc_path)
            
        if field == "breadcrumbs":
            if isinstance(value, BreadCrumb):
                config[field].append(value)
            elif isinstance(value, list):
                config[field].extend(value)
            else:
                raise TypeError("breadcrumbs type error!")
        else:
            config[field] = value


def global_variables(request):
    """
    Context processor that provides navigation-related context based on current path
    """
    context = genContextDict(request, CONFIG, process_config)
    return context

if __name__ == "__main__":
    from pprint import pprint
    _ = lambda s: str(s) # for testing in __name__ == '__main__'
    
    # pprint(CONFIG)
    # pprint(genContextDict("/project/mine", CONFIG, process_config))
    pprint(genContextDict(R("/project/1/plan/"), CONFIG, process_config))
    pprint(genContextDict(R("/project/1/plan/1"), CONFIG, process_config))
